// 1. 类型守卫函数
const isObject = (val: unknown): val is Record<string, any> => {
  return val !== null && typeof val === 'object' && !Array.isArray(val)
}

/**
 * 从一个源对象中根据另一个对象的key提取一个新的对象
 * @param origin 源对象
 * @param extract key提取对象
 * @returns Object
 */
const extractProps = <
  T extends Record<string, any>,
  K extends Record<string, any>
>(
  origin: T,
  extract: K
): Partial<T> => {
  // 判断是不是对象，不是抛异常
  if (!(isObject(origin) && isObject(extract)))
    throw new Error('origin or extract must be Object')

  const result = {} as Partial<T>
  const keys = Object.keys(extract)

  keys.forEach(key => {
    if (key in origin) {
      result[key as keyof T] = origin[key]
    }
  })

  return result
}

export { extractProps }
